package com.jelly.web.modules.monitor.online.service.impl;

import com.jelly.common.util.StringUtils;
import com.jelly.config.redis.session.RedisSessionDAO;
import com.jelly.web.modules.monitor.online.domain.OnLineUser;
import com.jelly.web.modules.monitor.online.service.IOnLineUserService;
import com.jelly.web.modules.staff.user.domain.User;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @创建人 ql
 * @创建时间 2018-10-08 17:52
 * @项目名称 jelly
 * @功能描述: 在线用户实现类
 **/
@Service
public class OnLineUserServiceImpl implements IOnLineUserService {

    @Autowired
    private RedisSessionDAO redisSessionDAO;

    @Override
    public List<OnLineUser> getOnLineUserAll(OnLineUser onLineUser) {
        Collection<Session> sessions = redisSessionDAO.getActiveSessions();

        List<OnLineUser> list = new ArrayList<>();
        for(Session session:sessions){
            OnLineUser onLineUsers = new OnLineUser();

            Object attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (attribute == null) {
                continue;
            }
            onLineUsers.setId(session.getId().toString());
            onLineUsers.setIp(session.getAttribute("ip").toString());
            onLineUsers.setLogLocation(session.getAttribute("logLocation").toString());
            User user = (User)((SimplePrincipalCollection)attribute).getPrimaryPrincipal();
            if(null != user){
                onLineUsers.setUserId(user.getUserId());
                onLineUsers.setUserName(user.getUserName());
                onLineUsers.setNickname(user.getNickname());
                onLineUsers.setLoginAccount(user.getLoginAccount());
                onLineUsers.setLoginDate(user.getLoginDate());
            }else {
                continue;
            }
            onLineUsers.setDate(session.getLastAccessTime());

            if(StringUtils.isNotBlank(onLineUser.getLoginAccount()) || StringUtils.isNotBlank(onLineUser.getUserName()) || StringUtils.isNotBlank(onLineUser.getNickname())){
                if(user.getLoginAccount().contains(onLineUser.getLoginAccount()) || user.getNickname().contains(onLineUser.getNickname()) ||user.getUserName().contains(onLineUser.getUserName())){
                    list.add(onLineUsers);
                    continue;
                }
            }else{
                list.add(onLineUsers);
            }
        }

        return list;
    }

    @Override
    public void delectOnLineUser(String id) {
        redisSessionDAO.delete(id);
    }

    @Override
    public void delectOnLineUser(List<String> ids) {

        for (String key : ids){
            redisSessionDAO.delete(key);
        }

    }

}
